package biz.yfsoft.app.fastframework.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import biz.yfsoft.app.fastframework.plugin.mongodb.MongoKit;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

public class RestController extends Controller{
	
	public DbPro db = Db.use("biz"); 
	
	public void test(){
		List<Record> users1 = db.find("select * from gr_login_info"); 
//		o.put("errno", 0);
//		o.put("message", "错了");
//		o.put("code", "ok!");
//		o.put("data", users1);
		
		renderJson(users1);
	}
	
	public void save(){
		String clz = this.getPara("class");
		String data = this.getPara("data");
		//HttpServletRequest req = this.getRequest();
		//String ak = req.getHeader("Fast-APP-KEY");
		//testet Version 1
		Record obj = new Record();
//		Map<String,Object> 
		obj.setColumns(getMapForJson(data));
		MongoKit.save(clz, obj);
		Map<String,Object> o = new HashMap<String,Object>();
		o.put("code", 0);
		renderJson(o);
	}
	
	public void signup(){
		//HttpServletRequest req = this.getRequest();
		//String ak = req.getHeader("Fast-APP-KEY");
		//testet Version 1
		Record obj = new Record();
		String username = this.getPara("username");
		String password = this.getPara("password");
		obj.set("username", username);
		obj.set("password", password);
//		Map<String,Object> 
		MongoKit.save("_user", obj);
		Map<String,Object> o = new HashMap<String,Object>();
		o.put("code", 0);
		renderJson(o);
	}
	
	public void fetch(){
		String clz = this.getPara("class");
		String id = this.getPara("_id");
		DBCollection c = MongoKit.getCollection(clz);
		
		DBObject data = c.findOne(new BasicDBObject("_id",id));
		renderJson(data);
	}
	
//	private String parse(DBObject data){
//		ObjectId oid = (ObjectId)data.removeField("_id");
//		data.put("_id", oid.toString());
//		return data.toString();
//	}
	
	public static Map<String, Object> getMapForJson(String jsonStr){
        JSONObject jsonObject ;
        try {
            jsonObject = JSONObject.parseObject(jsonStr);

            Map<String, Object> valueMap = new HashMap<String, Object>();
            for(String key:jsonObject.keySet()){
            	valueMap.put(key, jsonObject.get(key));
            }
            return valueMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
